package com.xbongbong.paas.lowcode.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.enums.ComboTypeEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.factory.LowCodeHandlerFieldFactory;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.abstracts.AbstractLowCodeHandlerFieldService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.util.ItemUtil;
import com.xbongbong.pro.lowcodeexecute.pojo.LowCodeExecuteServicePojo;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2021/03/18 15:08
 */
@Service("lowCodeHandlerCheckBoxGroupServiceImpl")
public class LowCodeHandlerCheckBoxGroupServiceImpl extends AbstractLowCodeHandlerFieldService {

    @PostConstruct
    public void register() {
        LowCodeHandlerFieldFactory.LOW_CODE_HANDLER_FIELD.put(FieldTypeEnum.CHECKBOX_GROUP.getType(), this);
        LowCodeHandlerFieldFactory.LOW_CODE_HANDLER_FIELD.put(FieldTypeEnum.COMBO_CHECK.getType(), this);
    }

    @Override
    public Object handlerField(FieldAttrEntity fieldAttrEntity, JSONObject data, LowCodeExecuteServicePojo lowCodeExecuteServicePojo) throws XbbException {
        List<Object> valueList = JSON.parseArray(JSON.toJSONString(data.get(fieldAttrEntity.getAttr())), Object.class);
        if (Objects.isNull(valueList)) {
            return null;
        }
        List<ItemPoJo> itemList = new ArrayList<>();
        valueList.forEach(item->{
            ItemPoJo itemPoJo = new ItemPoJo();
            if (Objects.equals(fieldAttrEntity.getComboType(), ComboTypeEnum.CUSTOM.getType())) {
                String text = ItemUtil.getTextByValue(item, fieldAttrEntity);
                itemPoJo.setValue(item);
                itemPoJo.setText(text);
            } else {
                if (ItemUtil.isUUID(item.toString())) {
                    String text = ItemUtil.getTextByValue(item, fieldAttrEntity);
                    itemPoJo.setValue(item);
                    itemPoJo.setText(text);
                } else {
                    itemPoJo.setValue(item);
                    itemPoJo.setText(String.valueOf(item));
                }
            }
            itemList.add(itemPoJo);
        });
        return itemList;
    }
}
